import { ProxyOptions } from 'vite'

export function setupViteServer(env: EnvType.ImportMeta) {
	return {
		host: true, // 指定服务器主机名
		port: env.VITE_PORT as unknown as number, // 指定服务器端口
		open: JSON.parse(env.VITE_OPEN), // 在服务器启动时自动在浏览器中打开应用程序
		hmr: true,
		proxy: resolveProxy(JSON.parse(env.VITE_PROXY))
	}
}

/**
 * 解析vite代理配置
 * @param proxyList
 */
function resolveProxy(proxyList: [string, string][]) {
	const proxy: Record<string, ProxyOptions> = {}
	for (const [prefix, target] of proxyList) {
		const isHttps = /^https:\/\//.test(target)
		proxy[prefix] = {
			target: target,
			changeOrigin: true,
			ws: true,
			rewrite: (path) => path.replace(new RegExp(`^${prefix}`), ''),
			// https is require secure=false
			...(isHttps ? { secure: false } : {})
		}
	}
	return proxy
}
